<?php

namespace cf\api\cart;

require_once dirname(__FILE__).'/../db.php';
require_once dirname(__FILE__).'/../cookie.php';
require_once dirname(__FILE__).'/../shop.php';

function create()
{
	global $user, $db;
	
	if ($user) {
		$cartId = \cf\query2var('SELECT id FROM cf_cart WHERE user_id=:uid',array('uid'=>$user->id()));
		if (!$cartId) {
			\cf\execQuery('INSERT INTO cf_cart (user_id) VALUES(:uid)',array('uid'=>$user->id()));
			$cartId = $db->lastInsertId();
		}
		if (!\cf\query2var('SELECT COUNT(*) FROM cf_products_in_cart WHERE cart_id=:cid',array('cid'=>$cartId))) {
			//the cart is empty check if there is a cart cookie 
		}
		return $cartId;
	} else {
		$c = \cf\Cookie::retrieve('cyberfish_cart');
		if (!$c) {
			$c = new \cf\Cookie('cyberfish_cart', 60*24*365);
			$c->setParam('ready',array());
			$c->set();
		}
		return $c;
	}
}

function set($products)
{
	global $user;

	if ($user) {
		clear();
		$cartId = create();
		$q = \cf\createQuery('INSERT INTO cf_products_in_cart (cart_id,product_id,amount) VALUES(:cid,:pid,:amt)');
		foreach ($products as $id => $amount) {
			$q->setParam('cid',$cartId);
			$q->setParam('pid',$id);
			$q->setParam('amt',$amount);
			$q->execute();
		}
	} else {
		$c = create();
		$c->setParam('ready',$products);
		$c->set();
	}
	return getList();
}

function add($productId, $amount=1)
{
	global $user;

	if ($user) {
		$cartId = create();
		$amt = \cf\query2var(
			'SELECT amount FROM cf_products_in_cart WHERE cart_id=:cid AND product_id=:pid AND status=0',
			array('cid'=>$cartId, 'pid'=>$productId)
		);
		if ($amt) {
			\cf\execQuery(
				'UPDATE cf_products_in_cart SET amount=:amt WHERE cart_id=:cid AND product_id=:pid',
				array('cid'=>$cartId, 'pid'=>$productId, 'amt'=>($amount+$amt))
			);
		} else {
			\cf\execQuery(
				'INSERT INTO cf_products_in_cart (cart_id,product_id,amount) VALUES(:cid,:pid,:amt)',
				array('cid'=>$cartId, 'pid'=>$productId, 'amt'=>$amount)
			);
		}
		
	} else {
		$c = create();
		$products = $c->getParam('ready');
		if (array_key_exists($productId, $products)) {
			$products[$productId] += (int)$amount;
		}
		else {
			$products[$productId] = (int)$amount;
		}
		$c->setParam('ready',$products);
		$c->set();
	}
	return getList();
}

function del($productId)
{
	global $user;
	
	if ($user) {
		$cartId = create();
		\cf\execQuery(
			'DELETE FROM cf_products_in_cart WHERE cart_id=:cid AND product_id=:pid',	
			array('cid'=>$cartId, 'pid'=>$productId)
		);
	} else {
		$c = create();
		$products = $c->getParam('ready');
		if (array_key_exists($productId, $products)) {
			unset($products[$productId]);
		}
		$c->setParam('ready',$products);
		$c->set();
	}
	return getList();
}

function getList()
{
	global $user;
	
	$ids = array();
	if ($user) {
		$cid = create();
		$products = \cf\query2arrays(
			'SELECT product_id, amount FROM cf_products_in_cart WHERE cart_id=:cid',
			array('cid'=>$cid),
			false,
			'product_id'
		);
		$productIDs = array();
		foreach ($products as $id => $p) {
			$productIDs[$id] = $p['amount'];
		}
	} else {
		$c = create();
		$productIDs = $c->getParam('ready');
	}
	$cart = array();
	$total_amount = 0;
	$total_price = 0;
	foreach ($productIDs as $id => $amount) {
		$product = new \cf\Product($id);
		$cart[] = array(
			'id' => $product->id(),
			'name' => $product->fullName(),
			'amount' => $amount,
			'price' => $product->price(),
			'image' => $product->image(),
			'manufacturerName' => $product->manufacturerName(),
			'total_price' => $product->price() * $amount
		);
		$total_amount += $amount;
		$total_price += ($product->price() * $amount);
	}
	return array_merge(array(array('total_amount'=>$total_amount, 'total_price'=>$total_price)),$cart);
}

function clear()
{
	global $user;
	
	if ($user) {
		\cf\execQuery('DELETE FROM cf_cart WHERE user_id=:uid',array('uid'=>$user->id()));
	} else {
		$c = \cf\Cookie::retrieve('cyberfish_cart');
		if ($c) {
			$c->delParam('ready');
			$c->setParam('ready',array());
			$c->set();
		}
	}
	return getList();
}



function order($name, $email='', $phone='', $address='', $comments='')
{
	global $user, $db;
	
	$productList = '';
	$products = getList();
	for ($i=1; $i<count($products); ++$i) {
		$productList .= "{$products[$i]['id']} {$products[$i]['name']} [{$products[$i]['price']}] - {$products[$i]['amount']} <br>";
	}
	$productList .= "<br><strong>Итого</strong>: {$products[0]['total_price']}";
	
	\cf\execQuery("
		INSERT INTO cf_orders (created,customer_name, customer_email, customer_phone, customer_address, customer_comments, comments)
		VALUES(NOW(),:name, :email, :phone, :address, :comments, :products)",
		array('name'=>$name, 'email'=>$email, 'phone'=>$phone, 'address'=>$address, 'comments'=>$comments, 'products'=>$productList)
	);
	$id = $db->lastInsertId();
	
	clear();
	
	return $id;
}

?>